package com.learn.exec;

/**
 * 银行有一个账号
 * 有两个用户分别向同一个账户存3000元，每次存1000，存3次。每次存完打印账户余额
 *
 * 分析：
 * 1.线程：两个储户线程
 * 2.共享数据：账户余额
 * 3.线程安全问题：有
 */
class Account{
    private double balance;

    public Account(Double balance){
        this.balance = balance;
    }

    public void input(double amt){
        if(amt > 0){
            balance += amt;

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + "存钱成功，余额为" + balance);
        }
    }
}

class Customer implements Runnable{
    private Account acc;

    public Customer(Account acc) {
        this.acc = acc;
    }

    @Override
    public void  run() {
        synchronized (this) {
            for (int i = 0; i < 3; i++) {
                acc.input(1000);
            }
        }
    }
}

public class AccountTest {
    public static void main(String[] args) {
        Account account = new Account((double) 0);
        Customer customer = new Customer(account);

        Thread t1 = new Thread(customer);
        Thread t2 = new Thread(customer);
        t1.setName("张三");
        t2.setName("李四");

        t1.start();
        t2.start();
    }
}

